#include "picwidget.h"

PicWidget::PicWidget(QWidget *parent) : QWidget(parent)
{
    //设置强焦点
    setFocusPolicy(Qt::StrongFocus);
    //设置支持拖放
    setAcceptDrops(true);

    //定时器校验视频
    timerCheck = new QTimer(this);
    timerCheck->setInterval(10 * 1000);
    connect(timerCheck, SIGNAL(timeout()), this, SLOT(checkVideo()));

    image = QImage();
    checkLive = true;
    drawImage = true;
    fillImage = true;

    flowEnable = false;
    flowBgColor = "#000000";
    flowPressColor = "#5EC7D9";

    timeout = 20;
    borderWidth = 5;
    borderColor = "#000000";
    focusColor = "#22A3A9";
    bgColor = Qt::transparent;
    bgText = "实时视频";
    bgImage = QImage();

    //初始化解码线程
    this->initThread();
    //初始化悬浮条
    this->initFlowPanel();
    //初始化悬浮条样式
    this->initFlowStyle();
}

PicWidget::~PicWidget()
{

}

void PicWidget::resizeEvent(QResizeEvent *)
{
    //logger.write(MSG_DEFAULT, "resizeEvent ......");
    int height = 20;
    flowPanel->setGeometry(borderWidth, borderWidth, this->width() - (borderWidth * 2), height);
}

void PicWidget::enterEvent(QEvent *)
{
    //logger.write(MSG_DEFAULT, "enterEvent ......");
    if (flowEnable) {
        flowPanel->setVisible(true);
    }
}

void PicWidget::leaveEvent(QEvent *)
{
    //logger.write(MSG_DEFAULT, "leaveEvent ......");
    if (flowEnable) {
        flowPanel->setVisible(false);
    }
}

void PicWidget::dropEvent(QDropEvent *event)
{
    //拖放完毕鼠标松开的时候执行
    //判断拖放进来的类型,取出文件,进行播放
    //logger.write(MSG_DEFAULT, "dropEvent ......");
    QString url;
    if(event->mimeData()->hasUrls()) {
        url = event->mimeData()->urls().first().toLocalFile();
    } else if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")) {
        QTreeWidget *treeWidget = (QTreeWidget *)event->source();
        if (treeWidget != 0) {
            url = treeWidget->currentItem()->data(0, Qt::UserRole).toString();
        }
    }

    if (!url.isEmpty()) {
        emit fileDrag(url);
        this->restart(url);
    }
}

void PicWidget::dragMoveEvent(QDragMoveEvent *event)
{
    //logger.write(MSG_DEFAULT, "dragMoveEvent ......");
}

void PicWidget::dragEnterEvent(QDragEnterEvent *event)
{
    //拖曳进来的时候先判断下类型,非法类型则不处理
    //logger.write(MSG_DEFAULT, "dragEnterEvent ......");
    if(event->mimeData()->hasFormat("application/x-qabstractitemmodeldatalist")) {
        event->setDropAction(Qt::CopyAction);
        event->accept();
    } else if (event->mimeData()->hasFormat("text/uri-list")) {
        event->setDropAction(Qt::LinkAction);
        event->accept();
    } else {
        event->ignore();
    }
}

void PicWidget::paintEvent(QPaintEvent *)
{
    //logger.write(MSG_DEFAULT, "paintEvent ......");
    //如果不需要绘制
    if(!drawImage)
        return;

    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing);

    //绘制边框
    drawBorder(&painter);
    if(!image.isNull()) {
        //绘制背景图片
        drawImg(&painter, image);
    } else {
        drawBg(&painter);
    }
}

void PicWidget::drawBorder(QPainter *painter)
{
    if (borderWidth == 0) {
        return;
    }

    painter->save();
    QPen pen;
    pen.setWidth(borderWidth);
    pen.setColor(hasFocus() ? focusColor : borderColor);
    painter->setPen(pen);
    painter->drawRect(rect());
    painter->restore();
}

void PicWidget::drawBg(QPainter *painter)
{
    painter->save();
    if (bgColor != Qt::transparent) {
        painter->fillRect(rect(), bgColor);
    }

    //背景图片为空则绘制文字,否则绘制背景图片
    if (bgImage.isNull()) {
        painter->setFont(this->font());
        painter->setPen(palette().windowText().color());
        painter->drawText(rect(), Qt::AlignCenter, bgText);
    } else {
        //居中绘制
        int x = rect().center().x() - bgImage.width() / 2;
        int y = rect().center().y() - bgImage.height() / 2;
        QPoint point(x, y);
        painter->drawImage(point, bgImage);
    }

    painter->restore();
}

void PicWidget::drawImg(QPainter *painter, QImage img)
{
    painter->save();
    int offset = borderWidth * 1 + 0;
    if(fillImage) {
        QRect rect(offset / 2, offset / 2, width() - offset, height() - offset);
        painter->drawImage(rect, img);
    } else {
        //按照比例自动居中绘制
        img = img.scaled(width() - offset, height() - offset, Qt::KeepAspectRatio);
        int x = rect().center().x() - img.width() / 2;
        int y = rect().center().y() - img.height() / 2;
        QPoint point(x, y);
        painter->drawImage(point, img);
    }
    painter->restore();
}

void PicWidget::initThread()
{

}

void PicWidget::initFlowPanel()
{
    //顶部工具栏,默认隐藏,鼠标移入显示移除隐藏
    flowPanel = new QWidget(this);
    flowPanel->setObjectName("flowPanel");
    flowPanel->setVisible(false);

    //用布局顶住,左侧弹簧
    QHBoxLayout *layout = new QHBoxLayout;
    layout->setSpacing(2);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addStretch();
    flowPanel->setLayout(layout);

    //按钮集合名称,如果需要新增按钮则在这里增加即可
    QList<QString> btns;
    btns << "btnFlowVideo" << "btnFlowSnap" << "btnFlowSound" << "btnFlowAlarm" << "btnFlowClose";

    //有多种办法来设置图片,qt内置的图标+自定义的图标+图形字体
    //既可以设置图标形式,也可以直接图形字体设置文本
#if 0
    QList<QIcon> icons;
    icons << QApplication::style()->standardIcon(QStyle::SP_ComputerIcon);
    icons << QApplication::style()->standardIcon(QStyle::SP_FileIcon);
    icons << QApplication::style()->standardIcon(QStyle::SP_DirIcon);
    icons << QApplication::style()->standardIcon(QStyle::SP_DialogOkButton);
    icons << QApplication::style()->standardIcon(QStyle::SP_DialogCancelButton);
#else
    QList<int> icons;
    icons << 0xe68d << 0xe672 << 0xe674 << 0xea36 << 0xe74c;

    //判断图形字体是否存在,不存在则加入
    QFont iconFont;
    QFontDatabase fontDb;
    if (!fontDb.families().contains("iconfont")) {
        int fontId = fontDb.addApplicationFont(":/image/iconfont.ttf");
        QStringList fontName = fontDb.applicationFontFamilies(fontId);
        if (fontName.count() == 0) {
            qDebug() << "load iconfont.ttf error";
        }
    }

    if (fontDb.families().contains("iconfont")) {
        iconFont = QFont("iconfont");
        iconFont.setPixelSize(17);
#if (QT_VERSION >= QT_VERSION_CHECK(4,8,0))
        iconFont.setHintingPreference(QFont::PreferNoHinting);
#endif
    }
#endif

    for(int i = 0; i < btns.size(); i++) {
        QPushButton *btn = new QPushButton;
        //绑定按钮单击事件,用来发出信号通知
        connect(btn, SIGNAL(clicked(bool)), this, SLOT(btnInnerClicked()));
        //设置标识,用来区别按钮
        btn->setObjectName(btns.at(i));
        //设置固定宽度
        btn->setFixedWidth(20);
        //设置拉伸策略使得填充
        btn->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
        //设置焦点策略为无焦点,避免单击后焦点跑到按钮上
        btn->setFocusPolicy(Qt::NoFocus);
#if 0
        //设置图标大小和图标
        btn->setIconSize(QSize(16, 16));
        btn->setIcon(icons.at(i));
#else
        btn->setFont(iconFont);
        btn->setText((QChar)icons.at(i));
#endif
        //将按钮加到布局中
        layout->addWidget(btn);
    }

}

void PicWidget::initFlowStyle()
{
    //设置样式以便区分,可以自行更改样式,也可以不用样式
    QStringList qss;
    QString rgba = QString("rgba(%1,%2,%3,150)").arg(flowBgColor.red()).arg(flowBgColor.green()).arg(flowBgColor.blue());
    qss.append(QString("#flowPanel{background:%1;border:none;}").arg(rgba));
    qss.append(QString("QPushButton{border:none;padding:0px;background:rgba(0,0,0,0);}"));
    qss.append(QString("QPushButton:pressed{color:%1;}").arg(flowPressColor.name()));
    flowPanel->setStyleSheet(qss.join(""));
}

void PicWidget::setUrl(const QString &url)
{
    this->setProperty("url", url);
}

void PicWidget::setDrawImage(bool drawImage)
{
    this->drawImage = drawImage;
}

void PicWidget::setFillImage(bool fillImage)
{
    this->fillImage = fillImage;
}

void PicWidget::setFlowEnable(bool flowEnable)
{
    this->flowEnable = flowEnable;
}

void PicWidget::setFlowBgColor(const QColor &flowBgColor)
{
    this->flowBgColor = flowBgColor;
}

void PicWidget::setFlowPressColor(const QColor &flowPressColor)
{
    this->flowPressColor = flowPressColor;
}

void PicWidget::setBorderWidth(int borderWidth)
{
    this->borderWidth = borderWidth;
}

void PicWidget::setBorderColor(const QColor &borderColor)
{
    this->borderColor = borderColor;
}

void PicWidget::setFocusColor(const QColor &focusColor)
{
    this->focusColor = focusColor;
}

void PicWidget::setBgColor(const QColor &bgColor)
{
    this->bgColor = bgColor;
}

void PicWidget::setBgText(const QString &bgText)
{
    this->bgText = bgText;
}

void PicWidget::setBgImage(const QImage &bgImage)
{
    this->bgImage = bgImage;
}

QImage PicWidget::getImage() const
{
    return this->image;
}

QString PicWidget::getUrl() const
{
    return this->property("url").toString();
}

bool PicWidget::getDrawImage() const
{
    return this->drawImage;
}

bool PicWidget::getFillImage() const
{
    return this->fillImage;
}

bool PicWidget::getFlowEnable() const
{
    return this->flowEnable;
}

QColor PicWidget::getFlowBgColor() const
{
    return this->flowBgColor;
}

QColor PicWidget::getFLowPressColor() const
{
    return this->flowPressColor;
}

int PicWidget::getTimeout() const
{
    return this->timeout;
}

int PicWidget::getBorderWidth() const
{
    return this->borderWidth;
}

QColor PicWidget::getBorderColor() const
{
    return this->borderColor;
}

QColor PicWidget::getFocusColor() const
{
    return this->focusColor;
}

QColor PicWidget::getBgColor() const
{
    return this->bgColor;
}

QString PicWidget::getBgText() const
{
    return this->bgText;
}

QImage PicWidget::getBgImage() const
{
    return this->bgImage;
}

void PicWidget::open()
{
    clear();

    //如果是图片则只显示图片就行
    image = QImage(this->property("url").toString());
    if (!image.isNull()) {
        this->update();
        return;
    }

    if (checkLive) {
        timerCheck->start();
    }

    this->setProperty("isPause", false);
}

void PicWidget::pause()
{

}

void PicWidget::next()
{

}

void PicWidget::close()
{

}

void PicWidget::restart(const QString &url, int delayOpen)
{
    //关闭视频
    close();
    //重新设置播放地址
    setUrl(url);

    //打开视频
    if (delayOpen > 0) {
        QTimer::singleShot(delayOpen, this, SLOT(open()));
    } else {
        open();
    }
}

void PicWidget::clear()
{

}

void PicWidget::snap(const QString &fileName)
{

}

void PicWidget::checkVideo()
{
    QDateTime now = QDateTime::currentDateTime();
    QDateTime lastTime = now;
    int sec = lastTime.secsTo(now);
    if (sec >= timeout) {
        restart(this->getUrl());
    }
}

void PicWidget::btnInnerClicked()
{

}

